/*
 * ex020102_forkvar.c
 */
#include <stdio.h>

#include <sys/types.h>
#include <unistd.h>

#include <errno.h>
#include <string.h>
#include <stdlib.h>		/* strcpy */

#define MAX_PROMPT_LEN 64

int g_flag = 1;

int main(int argc ,char *argv[])
{
	int pid = -1;
	char *prompt = NULL;

	prompt = (char*)malloc(MAX_PROMPT_LEN);
	if(NULL == prompt)
	{
		printf("memory maybe not enogh.\n");
		return -1;
	}

	strncpy(prompt, "I am a starting process.", MAX_PROMPT_LEN);

	printf("g_flag:%d, addr:%p; prompt:%s , addr:%p\n", g_flag, &g_flag, prompt, prompt);

	pid = fork();
	if(pid == 0)
	{
		// in child 
		printf("here in child ,my pid is %d\n", getpid());
		printf("[pid:%d] g_flag:%d, addr:%p; prompt:%s , addr:%p\n", getpid(), g_flag, &g_flag, prompt, prompt);
		g_flag = 2;
		free(prompt);
		prompt = NULL;

		sleep(10);
	}
	else if(pid > 0)
	{
		// in parent
		printf("here in parent, my pid %d, child pid is %d\n", getpid(), pid);
	        printf("[pid:%d] g_flag:%d, addr:%p; prompt:%s , addr:%p\n", getpid(), g_flag, &g_flag, prompt, prompt);

		sleep(10);
	}
	else
	{
		// error
		printf("fork error[%s]\n",strerror(errno));
	}

	
	printf("[pid:%d] g_flag:%d, addr:%p; prompt:%s , addr:%p\n", getpid(), g_flag, &g_flag, prompt, prompt);
	if(NULL != prompt)
		free(prompt);
	return 0;
}
